//
//  EmoticonTextView.swift
//  SinaWebo
//
//  Created by mis on 16/3/24.
//  Copyright © 2016年 mis. All rights reserved.
//

import UIKit

class EmoticonTextView: UITextView {
    
    func fullText() -> String {
        let attrText = attributedText
        var strMM = String()
        attrText.enumerateAttributesInRange(NSMakeRange(0, attrText.length), options: []) { (dict, range, _) -> Void in
            if let attachment = dict["NSAttachment"] as? EmoticonAttachment {
                let text = attachment.chs
                strMM += (text ?? "")
            }else {
                let str = (attrText.string as NSString).substringWithRange(range)
                strMM += str
            }
        }
        return strMM
    }
    
    func insertEmoticon(emoticon: Emoticon) {
        if emoticon.isEmpty {
            return
        }
        
        if emoticon.isRemove {
            deleteBackward()
            return
        }
        
        if emoticon.code != nil {
            replaceRange(selectedTextRange!, withText: emoticon.emojiStr ?? "")
            return
        }
        
        let attachment = EmoticonAttachment()
        let imageText = attachment.emoticonimageText(emoticon, font: font!)
        let range = selectedRange
        let strM = NSMutableAttributedString(attributedString: attributedText)
        strM.replaceCharactersInRange(range, withAttributedString: imageText)
        attributedText = strM
        selectedRange = NSMakeRange(range.location + 1, 0)
    }
}
